package ceshi;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Person {
    private int studentId;
    private String name;

    public Person() {
    }

    public Person(int studentId, String name) {
        this.studentId = studentId;
        this.name = name;
    }

    private String privateMatched() {
        // 随机生成一个字符串，这里只是简单示例，实际中可以使用更复杂的随机生成方法
        return "randomString" + Math.random();
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


public class ReflectionDemo {
    public static void main(String[] args) {
        try {
            // 获取 Person 类的 Class 对象
            Class<?> personClass = Class.forName("ceshi.Person");//这是因为 Class.forName 需要完整的类名，包括包名。

            // 创建 Person 对象
            Object personObj = personClass.getConstructor().newInstance();

            // 访问私有属性
            Field studentIdField = personClass.getDeclaredField("studentId");
            studentIdField.setAccessible(true);
            studentIdField.set(personObj, 123);

            Field nameField = personClass.getDeclaredField("name");
            nameField.setAccessible(true);
            nameField.set(personObj, "John");

            // 调用私有方法
            Method privateMethod = personClass.getDeclaredMethod("privateMatched");
            privateMethod.setAccessible(true);
            String result = (String) privateMethod.invoke(personObj);
            System.out.println("Result of private method: " + result);

            // 打印修改后的属性值
            System.out.println("Student ID: " + ((Person) personObj).getStudentId());
            System.out.println("Name: " + ((Person) personObj).getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}